﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using Microhard.Core.DBUtility;

namespace Microhard.Core.Printer.POS
{
    public class POSPrinterTool
    {
        //定义指令
        private byte[] _initPrint = System.Text.Encoding.Default.GetBytes(((char)27).ToString() + ((char)64).ToString()); //初始化打印机
        private byte[] _fonts = new byte[] { 27, 82, 15 };// 选择字体
        private byte[] _size = new byte[] { 29, 33, 1 };//字体大小
        private byte[] _cut = new byte[] { 29, 86, 1, 49 };//切纸

        public ExecutedResult SendToPrint(string ip, int port, IPOSContentTemplate printTemplate, object model)
        {
            var content = printTemplate.CreateContent(model);
            return SendToPrint(ip, port, content);
        }

        public ExecutedResult SendToPrint(string ip, int port, string printContent)
        {
            ExecutedResult result = new ExecutedResult();
            TcpClient tcp = new TcpClient();
            NetworkStream sendStream = null;
            try
            {
                //连接打印机
                tcp.Connect(ip, port);
                sendStream = tcp.GetStream();
                //打印初始化
                sendStream.Write(_initPrint, 0, _initPrint.Length);
                sendStream.Write(_fonts, 0, _fonts.Length);
                sendStream.Write(_size, 0, _size.Length);
                //打印内容
                var data = System.Text.Encoding.Default.GetBytes(printContent);
                sendStream.Write(data, 0, data.Length);//输出文字
                //切纸
                sendStream.Write(_cut, 0, _cut.Length);
            }
            catch (Exception ex)
            {
                Log.Error("POSPrinterTool", ex);
                result.ErrorMsg.Add("POSPrinterTool", ex.Message);
            }
            finally
            {
                tcp.Close();
                sendStream.Close();
            }
            return result;
        }
    }
}
